package top.suven.http.oauth.authorize;


import top.suven.http.oauth.facade.OauthServiceFacade;
import top.suven.http.oauth.validator.AbstractOAuthResponseTypeValidator;
import top.suven.http.oauth.validator.ResponseTypeClientDetailsValidator;
import top.suven.http.oauth.vo.OAuthParameter;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.suven.base.core.spring.SpringUtil;


/**
 * @ClassName: OAuthAuthorizeCodeHandler.java
 * @Description: OAUTH2.0的认证服务, auth 请求验证
 * @Author suven.wang
 * @Date 2018/7/26 18:01
 * @Copyright: (c) 2018 gc by https://www.gc.com.cn/
 * @Version : 1.0.0
 *  --------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 *  --------------------------------------------------------
 */
public class OAuthAuthorizeCodeHandler extends AbstractOAuthAuthorizeHandler {

    private static final Logger logger = LoggerFactory.getLogger(OAuthAuthorizeCodeHandler.class);
    private OauthServiceFacade oauthService;


    public OAuthAuthorizeCodeHandler() {
        super();
        oauthService = SpringUtil.getBean(OauthServiceFacade.class);
    }

    @Override
    protected AbstractOAuthResponseTypeValidator getValidator() {
        return new ResponseTypeClientDetailsValidator(oauthRequest);
    }

    /**
     *  生成授权码 UUIDValueGenerator OR MD5Generator
     *  并保存到数据库中
     */

    @Override
    protected OAuthResponse handleResponse(){
        try {
            //生成授权码 UUIDValueGenerator OR MD5Generator
            String authorizationCode = new OAuthIssuerImpl(new MD5Generator()).authorizationCode();
            //保存授权码
            OAuthResponse body = this.getValidator().responseAuthorizationCode(authorizationCode);
            if(null != body){
                OAuthParameter parameter = oauthRequest.getOAuthParameter();
                if(null != parameter && parameter.getUserId() > 0){
                    parameter.setCode(authorizationCode);
                    oauthService.saveAuthorizationCode(parameter);
                    return body;
                }
            }
        }catch (Exception e){
            logger.error(" OAuthAuthorize Code Handler Response Exception [{}]", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证用户是否已经登陆;
     * @param validator
     * @return
     * @throws OAuthSystemException
     */
    @Override
    protected OAuthResponse handleAfterValidation(AbstractOAuthResponseTypeValidator validator) {

        return validator.getResponse();

    }




}